from django.db import transaction
from django.db.models import Sum
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from BYD_ERP.utils.get_inventory import get_inventory_by_goods
from sale_info.models import MonthlyProductionPlanModel, MonthlyProductionPlanItemModel


class MonthlyProductionPlanItemSerializer(serializers.ModelSerializer):
    """
        月度生产计划项目的序列化器
    """
    # cur_inventory这个属性只是用于查询（就是序列化），所以加上read_only=True
    # cur_inventory = serializers.SerializerMethodField(read_only=True, label='当前仓库中的库存')

    class Meta:
        model = MonthlyProductionPlanItemModel
        fields = '__all__'

'''
    def get_cur_inventory(self, obj):
        # 当前obj是：SaleOrderItemModel对象
        result = get_inventory_by_goods(obj.goods.id, obj.warehouse.id)
        # 如果result有就返回result，如果result没有就返回0。
        return result if result else 0
'''

class MonthlyProductionPlanSerializer(serializers.ModelSerializer):
    """
        新增和修改月度生产计划的序列化和反序列化
    """
    # write_only=True表示只是用于反序列化
    item_list = MonthlyProductionPlanItemSerializer(many=True)
    # goods_info只是在序列化的时候用到，所以需要加上read_only=True
    # 月度生产计划列表中需要展示：商品信息，多个商品的名称+规格，中间使用逗号隔开
    goods_info = serializers.SerializerMethodField(read_only=True, label='包含月度生产计划中每个商品信息')

    class Meta:
        model = MonthlyProductionPlanModel
        fields = '__all__'

    def get_goods_info(self, obj):
        """
            商品信息：商品1名称+商品1规格，商品2名称+商品2规格，…………
        """
        # 使用.all()返回的是列表
        if obj.item_list.all():
            result = []
            for item in obj.item_list.all():
                result.append(item.name + (item.specification if item.specification else ''))
            return ','.join(result)
        return ''

    def create(self, validated_data):
        item_list = validated_data.pop('item_list')
        with transaction.atomic():
            production_plan = MonthlyProductionPlanModel.objects.create(**validated_data)
            print('-------------production_plan--------------')
            print(production_plan)
            for item in item_list:
                # item = validated_data.pop('item')
                print('---------------item---------------------')
                print(item)
                mpp = MonthlyProductionPlanItemModel.objects.create(monthly_production_plan=production_plan, **item)
                goods = item.get('goods')
                mpp.name = goods.name
                mpp.specification = goods.specification
                mpp.model_number = goods.model_number
                mpp.save()
        return production_plan

    def update(self, instance, validated_data):
        # instance：正在修改的月度生产计划
        if instance.status != '0':
            # sale_order月度生产计划的状态，0：未审核，1：已审核
            raise ValidationError('月度生产计划已经生效，不能修改')
        item_list = validated_data.pop('item_list')
        # 如果之前有老数据（之前新增的月度生产计划项目数据）是需要删除掉的
        old_list = instance.item_list.all()
        with transaction.atomic():
            if old_list.exists():
                # 把老数据删除
                old_list.delete()
            for item in item_list:
                mpp = MonthlyProductionPlanItemModel.objects.create(monthly_production_plan=instance, **item)
                goods = item.get('goods')
                mpp.name = goods.name
                mpp.specification = goods.specification
                mpp.model_number = goods.model_number
                mpp.units = goods.units
                mpp.units_name = goods.units_name
                mpp.save()
            result = super(MonthlyProductionPlanSerializer, self).update(instance=instance, validated_data=validated_data)
        return result


class MonthlyProductionPlanGetSerializer(serializers.ModelSerializer):
    """
        仅仅用于查询展示月度生产计划详情的序列化器
    """
    item_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MonthlyProductionPlanModel
        fields = '__all__'

    def get_item_list(self, obj):
        result = []  # 返回的是列表，列表中是多个字典
        if obj.item_list.all().exists():
            for item in obj.item_list.all():
                # item是一个SaleOrderItemModel的对象
                # 有一部分信息在SaleOrderItemModel里面没有
                # 只有在GoodsModel里面有：开票名称、开票型号、长度等
                item_dict = {}
                goods = item.goods
                warehouse = item.warehouse
                item_dict['goods'] = goods.id
                item_dict['name'] = goods.name  # 国标名称
                item_dict['specification'] = goods.specification  # 件号
                item_dict['model_number'] = goods.model_number  # 型号
                item_dict['brand'] = goods.brand  # 品牌
                item_dict['units'] = goods.units.basic_name
                item_dict['local_inventory'] = item.local_inventory  # 永驰库存/本地库存
                item_dict['monthly_production_plan_count'] = item.monthly_production_plan_count
                item_dict['remark'] = item.remark
                # 该商品的总库存数量
                item_dict['cur_inventory_total'] = get_inventory_by_goods(goods.id)
                item_dict['cur_inventory_peitao'] = get_inventory_by_goods(goods.id, warehouse_id=1)

                result.append(item_dict)
        return result
